//
//  AppDelegate.m
//  原生本地推送
//
//  Created by Hello Cai on 2019/6/1.
//  Copyright © 2019 Hello Cai. All rights reserved.
//

#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    if (@available(iOS 10.0, *)) {
        //iOS10及以上，推送可以带图片
        [self newVersionPush];
    }else{
        //iOS10以下
        [self lowVersionPush];
    }
    NSLog(@"++++_____++++");
    return YES;
}

-(void)lowVersionPush{
    //申请权限。弹出弹窗：xxx想给你发送通知，"通知"可能包括提醒、声音和图标标记。会有按钮允许和不允许选择，若点击不允许，则不会推送消息。
    //设置通知的类型为弹窗提示、声音提示、应用图标数字提示
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
    // 授权弹窗
    [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    
    
    // 1.创建通知
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    
    // 2.设置通知的必选参数
    // 设置通知显示的内容
    localNotification.alertBody = @"通知的内容(body、body、body、body)";
    // 设置通知的发送时间
    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:3];
    
    localNotification.alertAction = @"赶紧的了!";
    
    localNotification.alertTitle = @"通知的标题";
    localNotification.applicationIconBadgeNumber = 1;
    
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    // 3.发送通知
    // 方式一: 根据通知的发送时间(fireDate)发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    // 方式二: 立即发送通知
//    [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}

-(void)newVersionPush API_AVAILABLE(ios(10.0))
{
    //1.申请权限（弹出弹窗：xxx想给你发送通知，"通知"可能包括提醒、声音和图标标记。这些可在设置中配置（会有按钮允许和不允许选择），询问用户权限。若点击不允许，则不会推送消息）
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error){}];
    
    //2.初始化通知
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.badge = @1;
    content.title = @"通知的标题";
    content.body = @"通知的内容(body、body、body、body)";   //如果不填写body,则不会弹出通知
    UNNotificationSound *sound = [UNNotificationSound defaultSound]; //系统的声音
    content.sound = sound;
    
    //3.下载图片
    //3.1获取图片
    NSString * imageUrlString = @"https://img1.doubanio.com/img/musician/large/22817.jpg";
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlString]];
    
    //3.2图片保存到沙盒(保存在沙盒的推送图片 会在推送完成后自动删除)
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *localPath = [documentPath stringByAppendingPathComponent:@"localNotificationImage.jpg"];
    [imageData writeToFile:localPath atomically:YES];
    
    //3.3设置通知的attachment(附件)，url表示文件路径
    if (localPath && ![localPath isEqualToString:@""]) {
        UNNotificationAttachment * attachment = [UNNotificationAttachment attachmentWithIdentifier:@"photo" URL:[NSURL URLWithString:[@"file://" stringByAppendingString:localPath]] options:nil error:nil];
        if (attachment) {
            content.attachments = @[attachment];
        }
    }
    
    //4.设置触发模式（2秒后触发）
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
    
    //5.推送
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"pusswzy" content:content trigger:trigger];
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (error) {
            NSLog(@"%@", error);
        }
    }];
    
    //设置代理
    center.delegate = self;
}

#pragma mark - iOS10及以上 收到通知（本地和远端） UNUserNotificationCenterDelegate
//重写该方法，调用completionHandler，前台会下滑弹出推送消息
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)){
    // 有这句，推送会在前台展示
    completionHandler(UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionSound);

    NSDictionary * userInfo = notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            NSLog(@"iOS10 前台收到远程通知:%@", userInfo);
        }else{
            NSLog(@"iOS10 前台收到本地通知:%@", userInfo);
        }
    }
}
//点击消息横幅，进入app后便会来到该方法。一般处理业务逻辑，如跳转对应的界面
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){
    NSLog(@"实现这个，只有iOS10及以上才能进来----");
    completionHandler();
}

#pragma mark - iOS10以下
//在后台时，点击推送消息。或在前台时，`收到推送消息`回调该方法（在前台，系统10以下不会下滑弹出推送消息）
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    NSLog(@"进来了----");
}






- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    #pragma mark -->NSLog(@"\n ===> 程序挂起 !");  比如:当有电话进来或者锁屏，这时你的应用程会挂起，在这时，UIApplicationDelegate委托会收到通知，调用 applicationWillResignActive 方法，你可以重写这个方法，做挂起前的工作，比如关闭网络，保存数据。
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    #pragma mark --> NSLog(@"\n ===> 程序进入后台 !");
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    #pragma mark --> NSLog(@"\n ===> 程序进入前台 !");
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    #pragma mark -->  NSLog(@"\n ===> 程序重新激活 !"); 应用程序在启动时，在调用了 applicationDidFinishLaunching 方法之后也会调用 applicationDidBecomeActive 方法，所以你要确保你的代码能够分清复原与启动，避免出现逻辑上的bug。(大白话就是说:只要启动app就会走此方法)。
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    #pragma mark --> 当用户按下按钮，或者关机，程序都会被终止。当一个程序将要正常终止时会调用 applicationWillTerminate 方法。但是如果长主按钮强制退出，则不会调用该方法。这个方法该执行剩下的清理工作，比如所有的连接都能正常关闭，并在程序退出前执行任何其他的必要的工作.
}


@end
